package pers.qianyu.diytomcat.watcher;

import cn.hutool.core.io.*;
import cn.hutool.core.io.watch.*;
import cn.hutool.core.util.*;
import pers.qianyu.diytomcat.catalina.*;
import pers.qianyu.diytomcat.constants.*;

import java.io.*;
import java.nio.file.*;

import static java.nio.file.StandardWatchEventKinds.*;

/**
 * @author mizzle rain
 * @date 2021-01-16 18:55
 */
public class WarFileWatcher {
    private WatchMonitor monitor;

    public WarFileWatcher(Host host) {
        this.monitor = WatchUtil.createAll(Locations.WEBAPPS_FOLDER, 1, new Watcher() {
            @Override
            public void onCreate(WatchEvent<?> event, Path currentPath) {
                dealWith(event, currentPath);
            }

            @Override
            public void onModify(WatchEvent<?> event, Path currentPath) {
                dealWith(event, currentPath);
            }

            @Override
            public void onDelete(WatchEvent<?> event, Path currentPath) {
                dealWith(event, currentPath);
            }

            @Override
            public void onOverflow(WatchEvent<?> event, Path currentPath) {
                dealWith(event, currentPath);
            }

            private void dealWith(WatchEvent<?> event, Path currentPath) {
                synchronized (WarFileWatcher.class) {
                    String fileName = event.context().toString();
                    if (ENTRY_CREATE.equals(event.kind()) && fileName.toLowerCase().endsWith(".war")) {
                        File file = FileUtil.file(Locations.WEBAPPS_FOLDER, fileName);
                        host.loadWarFile(file);
                        System.out.println(StrUtil.format("项目{}动态部署成功", file.getAbsolutePath()));
                    }
                }
            }
        });
    }

    public void start() {
        monitor.start();
    }

    public void stop() {
        monitor.interrupt();
    }
}
